<template>
  <div class="discussion-publish-page">
    <div class="floating-shapes">
      <div class="shape shape-1"></div>
      <div class="shape shape-2"></div>
    </div>

    <div class="container">
      <div class="header">
        <div class="back-btn" @click="handleBack">
          <i class="mdi mdi-arrow-left"></i>
        </div>
        <h1 class="page-title">发布求助</h1>
      </div>

      <div class="post-form">
        <div class="form-group">
          <label for="post-title">标题</label>
          <input
              type="text"
              id="post-title"
              placeholder="请输入求助标题"
              v-model="formData.title"
          >
        </div>

        <div class="form-group">
          <label for="post-content">内容</label>
          <textarea
              id="post-content"
              placeholder="提出你的问题..."
              v-model="formData.content"
          ></textarea>
        </div>

        <div class="image-upload">
          <label>添加图片（可选）</label>
          <div
              class="upload-area"
              id="upload-area"
              @click="triggerFileInput"
              @dragover.prevent="handleDragOver"
              @dragleave="handleDragLeave"
              @drop.prevent="handleDrop"
              :style="{
              borderColor: isDragging ? '#1E88E5' : '#b3d9fc',
              background: isDragging ? 'rgba(30, 136, 229, 0.15)' : 'rgba(30, 136, 229, 0.05)'
            }"
          >
            <div class="upload-icon">
              <i class="mdi mdi-cloud-upload"></i>
            </div>
            <div class="upload-text">点击或拖拽图片到此处</div>
            <div v-if="uploadingImages" class="upload-progress">
              <div class="progress-bar" :style="{ width: uploadProgress + '%' }"></div>
              <div class="progress-text">上传中... {{ uploadProgress }}%</div>
            </div>
          </div>
          <input
              type="file"
              ref="fileInput"
              accept="image/*"
              multiple
              @change="handleFileSelect"
              style="display: none"
          >
          <div class="image-preview">
            <div
                v-for="(preview, index) in imagePreviews"
                :key="index"
                class="preview-item"
            >

              <div class="remove-image" @click="removeImage(index)">
                <i class="mdi mdi-close"></i>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="action-buttons">
        <button class="btn btn-outline" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="submitForm" :disabled="isSubmitting">
          <i class="mdi mdi-send" style="margin-right: 8px;"></i>
          {{ isSubmitting ? '发布中...' : '发布讨论' }}
        </button>
      </div>
    </div>

    <transition name="slide-notification">
      <div v-if="showSuccess" class="success-notification">
        <i class="mdi mdi-check-circle" style="margin-right: 8px;"></i> 发布成功！
      </div>
    </transition>

    <transition name="slide-notification">
      <div v-if="showError" class="error-notification">
        <i class="mdi mdi-alert-circle" style="margin-right: 8px;"></i> {{ errorMessage }}
      </div>
    </transition>
  </div>
</template>

<script>
import axios from '@/utils/axios';
import { client, getFileNameUUID } from '@/utils/alioss';

export default {
  name: 'DiscussionPublish',
  data() {
    return {
      formData: {
        title: '',
        content: '',
        type: 3,
        images: ''
      },
      selectedFiles: [],
      imagePreviews: [],
      isDragging: false,
      isSubmitting: false,
      uploadingImages: false,
      uploadProgress: 0,
      showSuccess: false,
      showError: false,
      errorMessage: ''
    }
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click();
    },

    handleFileSelect(event) {
      this.handleFiles(event.target.files);
    },

    handleDragOver() {
      this.isDragging = true;
    },

    handleDragLeave() {
      this.isDragging = false;
    },

    handleDrop(event) {
      this.isDragging = false;
      this.handleFiles(event.dataTransfer.files);
    },

    handleFiles(files) {
      for (let i = 0; i < files.length; i++) {
        if (this.selectedFiles.length >= 9) {
          this.showErrorMsg('最多只能上传9张图片');
          break;
        }

        const file = files[i];
        if (!file.type.match('image.*')) continue;

        this.selectedFiles.push(file);

        const reader = new FileReader();
        reader.onload = (e) => {
          this.imagePreviews.push({
            file: file,
            url: e.target.result
          });
        };
        reader.readAsDataURL(file);
      }
    },

    removeImage(index) {
      this.selectedFiles.splice(index, 1);
      this.imagePreviews.splice(index, 1);
      this.uploadedImageUrls.splice(index, 1);
    },

    async uploadImagesToOSS() {
      this.uploadingImages = true;
      this.uploadProgress = 0;
      const uploadedUrls = [];
      const ossClient = client();

      const totalFiles = this.selectedFiles.length;
      let uploadedCount = 0;

      for (const file of this.selectedFiles) {
        try {
          // 生成唯一文件名
          const fileName = getFileNameUUID();
          const fileExtension = file.name.substring(file.name.lastIndexOf('.'));
          const fullName = `Posts/${fileName}${fileExtension}`;

          // 上传到阿里云OSS
          const result = await ossClient.put(fullName, file, {
            progress: (p) => {
              // 计算整体上传进度
              const fileProgress = p * 100;
              const overallProgress = (uploadedCount + p) / totalFiles * 100;
              this.uploadProgress = Math.round(overallProgress);
            }
          });

          // 存储上传成功的URL
          uploadedUrls.push(result.url);
          uploadedCount++;

        } catch (error) {
          console.error('图片上传失败:', error);
          this.showErrorMsg('图片上传失败，请重试');
          throw error;
        }
      }

      this.uploadingImages = false;
      this.uploadProgress = 0;
      return uploadedUrls;
    },

    async submitForm() {
      // 验证表单
      if (!this.formData.title || !this.formData.content) {
        this.showErrorMsg('请填写标题和内容');
        return;
      }

      this.isSubmitting = true;
      this.hideError();

      try {
        // 1. 如果有图片，先上传到阿里云OSS
        let imageUrls = [];
        if (this.selectedFiles.length > 0) {
          imageUrls = await this.uploadImagesToOSS();
        }

        // 2. 获取token（假设存储在localStorage）
        const token = localStorage.getItem('token');
        if (!token) {
          throw new Error('未登录，请先登录');
        }

        // 3. 构建请求数据对象
        const requestData = {
          title: this.formData.title,
          content: this.formData.content,
          type: this.formData.type
        };

        // 添加图片URL数组 - 转换为JSON字符串
        if (imageUrls.length > 0) {
          requestData.images = JSON.stringify(imageUrls);
        }

        // 4. 发送请求到后端 - 使用普通对象格式
        const response = await axios.post('/api/posts/publish', requestData, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'token': token
          },
          transformRequest: [(data) => {
            // 将对象转换为表单编码的字符串
            let formData = new FormData();
            for (let key in data) {
              formData.append(key, data[key]);
            }
            return formData;
          }]
        });
        console.log(response)
        // 5. 处理响应
        if (response.code === 200) {
          this.showSuccess = true;
          setTimeout(() => {
            this.showSuccess = false;
            this.$router.push('/home'); // 发布成功后跳转到首页
          }, 1500);
        } else {
          throw new Error(response.data.message || '发布失败');
        }
      } catch (error) {
        console.error('发布失败:', error);
        this.showErrorMsg(error.response?.data?.message || error.message || '发布失败，请重试');
      } finally {
        this.isSubmitting = false;
      }
    },

    showErrorMsg(message) {
      this.errorMessage = message;
      this.showError = true;
      setTimeout(() => {
        this.showError = false;
      }, 3000);
    },

    hideError() {
      this.showError = false;
    },

    handleBack() {
      if (this.formData.title || this.formData.content || this.selectedFiles.length > 0) {
        if (confirm('您有未保存的内容，确定要返回吗？')) {
          this.$router.back();
        }
      } else {
        this.$router.back();
      }
    },

    handleCancel() {
      this.$router.back();
    }
  }
}
</script>

<style scoped>
@import url('https://cdn.jsdelivr.net/npm/@mdi/font@7.2.96/css/materialdesignicons.min.css');
@import url('https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700;800&display=swap');

:root {
  --primary: #1E88E5; /* 蓝色主色调 */
  --primary-gradient: linear-gradient(135deg, #1E88E5 0%, #64B5F6 100%); /* 蓝色渐变 */
  --secondary: #BBDEFB; /* 浅蓝色辅助色 */
  --accent: #E3F2FD; /* 极浅蓝强调色 */
  --dark: #0D47A1; /* 深蓝色文字 */
  --light: #F7FAFC; /* 浅蓝白色背景 */
  --community: #5B8CFF; /* 社区蓝色（保留原定义） */
  --transaction: #90CAF9; /* 交易浅蓝色 */
  --success: #4CAF50; /* 成功绿色（保持不变） */
  --warning: #FF9800; /* 警告黄色（保持不变） */
  --danger: #F44336; /* 危险红色（保持不变） */
  --card-shadow: 0 8px 20px rgba(30, 136, 229, 0.2); /* 蓝色阴影 */
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Nunito', 'PingFang SC', sans-serif;
  -webkit-tap-highlight-color: transparent;
}

.discussion-publish-page {
  background: linear-gradient(135deg, #E3F2FD 0%, #F7FAFC 100%); /* 蓝白渐变背景 */
  color: #333;
  min-height: 100vh;
  overflow-x: hidden;
  padding-bottom: env(safe-area-inset-bottom);
}

.container {
  width: 100%;
  max-width: 100%;
  padding: 15px;
  margin: 0 auto;
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-top: 10px;
  position: sticky;
  top: 0;
  z-index: 100;
  background: linear-gradient(135deg, #E3F2FD 0%, #F7FAFC 100%); /* 蓝白渐变背景 */
  padding-bottom: 10px;
}

.back-btn {
  width: 44px;
  height: 44px;
  background: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  color: var(--primary);
  font-size: 18px;
  cursor: pointer;
}

.page-title {
  font-size: 22px;
  font-weight: 800;
  background: #3A7BFF;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  flex: 1;
  text-align: center;
  margin-right: 44px;
}

/* 表单样式 */
.post-form {
  background: white;
  border-radius: 20px;
  padding: 20px;
  box-shadow: var(--card-shadow);
  margin-bottom: 20px;
  position: relative;
  overflow: hidden;
}

.post-form::before {
  content: '';
  position: absolute;
  top: -15px;
  right: -15px;
  width: 80px;
  height: 80px;
  background: var(--primary-gradient);
  border-radius: 50%;
  opacity: 0.1;
  z-index: 0;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
  z-index: 1;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 700;
  color: var(--dark);
  font-size: 16px;
}

input[type="text"], textarea {
  width: 100%;
  padding: 16px;
  border: 2px solid #e3f2fd;
  border-radius: 16px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: #f7fafc;
  -webkit-appearance: none;
}

input[type="text"]:focus, textarea:focus {
  border-color: var(--primary);
  outline: none;
  background: white;
  box-shadow: 0 4px 12px rgba(30, 136, 229, 0.1);
}

textarea {
  min-height: 120px;
  resize: vertical;
}

/* 图片上传 */
.image-upload {
  margin-bottom: 20px;
}

.upload-area {
  border: 2px dashed #b3d9fc;
  border-radius: 16px;
  padding: 25px 15px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(30, 136, 229, 0.05);
  position: relative;
  overflow: hidden;
}

.upload-area:active {
  background: rgba(30, 136, 229, 0.1);
  transform: scale(0.98);
}

.upload-icon {
  font-size: 36px;
  color: var(--primary);
  margin-bottom: 10px;
}

.upload-text {
  color: #666;
  font-weight: 600;
  font-size: 15px;
}

.upload-progress {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 6px;
  background: rgba(0, 0, 0, 0.1);
}

.progress-bar {
  height: 100%;
  background: var(--primary);
  transition: width 0.3s ease;
}

.progress-text {
  margin-top: 5px;
  font-size: 12px;
  color: var(--primary);
}

.image-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 15px;
}

.preview-item {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image {
  position: absolute;
  top: 5px;
  right: 5px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  cursor: pointer;
}

/* 隐私设置 */
.privacy-section {
  background: linear-gradient(135deg, rgba(30, 136, 229, 0.1) 0%, rgba(100, 181, 246, 0.1) 100%);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 20px;
  border: 2px solid rgba(30, 136, 229, 0.2);
}

.privacy-title {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.privacy-title i {
  font-size: 20px;
  color: var(--primary);
  margin-right: 10px;
}

.privacy-title h3 {
  font-size: 18px;
  font-weight: 800;
  color: var(--dark);
}

.privacy-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.privacy-option {
  background: white;
  border-radius: 14px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  position: relative;
  overflow: hidden;
}

.privacy-option.selected {
  border-color: var(--primary);
  box-shadow: 0 5px 15px rgba(30, 136, 229, 0.15);
}

.privacy-option::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: var(--primary-gradient);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.privacy-option.selected::before {
  opacity: 1;
}

.option-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.option-header input[type="radio"] {
  margin-right: 10px;
  width: 20px;
  height: 20px;
  accent-color: var(--primary);
}

.option-header label {
  margin-bottom: 0;
  font-size: 16px;
  cursor: pointer;
}

.option-desc {
  color: #666;
  font-size: 14px;
  margin-left: 30px;
}

.privacy-notice {
  display: flex;
  align-items: center;
  background: rgba(30, 136, 229, 0.1);
  color: var(--primary);
  padding: 12px;
  border-radius: 12px;
  margin-top: 15px;
  font-size: 14px;
  border: 1px dashed var(--primary);
}

.privacy-notice i {
  margin-right: 8px;
  font-size: 16px;
}

/* 按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
  position: sticky;
  bottom: 20px;
  z-index: 10;
}

.btn {
  flex: 1;
  padding: 16px;
  border: none;
  border-radius: 16px;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.btn:active:not(:disabled) {
  transform: scale(0.98);
}

.btn-primary {
  background: var(--primary-gradient);
  color: #3A7BFF;
  box-shadow: 0 5px 15px rgba(30, 136,

  229, 0.3);
}

.btn-primary:active:not(:disabled) {
  box-shadow: 0 3px 10px rgba(30, 136, 229, 0.4);
}

.btn-outline {
  background: transparent;
  border: 2px solid #b3d9fc;
  color: var(--primary);
}

.btn-outline:active {
  border-color: var(--primary);
  color: var(--primary);
}

/* 浮动形状 */
.floating-shapes {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: -1;
}

.shape {
  position: absolute;
  border-radius: 50%;
  opacity: 0.15;
}

.shape-1 {
  width: 80px;
  height: 80px;
  background: var(--primary);
  top: 10%;
  left: 5%;
  animation: float 15s infinite ease-in-out;
}

.shape-2 {
  width: 60px;
  height: 60px;
  background: var(--accent);
  bottom: 15%;
  right: 10%;
  animation: float 12s infinite ease-in-out reverse;
}

@keyframes float {
  0%, 100% { transform: translateY(0) rotate(0deg); }
  50% { transform: translateY(-15px) rotate(10deg); }
}

/* 通知提示 */
.success-notification {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  background: #e3f2fd;
  color: #3A7BFF;
  border-radius: 12px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.2);
  z-index: 1000;
  font-weight: 600;
  font-size: 15px;
  transition: transform 0.3s ease;
}

.error-notification {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  background: #e3f2fd;
  color: #e74c3c;
  border-radius: 12px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.2);
  z-index: 1000;
  font-weight: 600;
  font-size: 15px;
  transition: transform 0.3s ease;
}

.slide-notification-enter-active,
.slide-notification-leave-active {
  transition: transform 0.3s ease;
}

.slide-notification-enter-from,
.slide-notification-leave-to {
  transform: translateX(100%);
}

/* 响应式调整 */
@media (max-width: 480px) {
  .container {
    padding: 12px;
  }

  .post-form {
    padding: 18px;
    border-radius: 18px;
  }

  .page-title {
    font-size: 20px;
  }

  input[type="text"], textarea {
    padding: 14px;
    font-size: 16px;
  }

  .privacy-section {
    padding: 16px;
  }

  .privacy-option {
    padding: 14px;
  }

  .btn {
    padding: 14px;
    font-size: 15px;
  }

  .preview-item {
    width: 70px;
    height: 70px;
  }
}

/* 安全区域适配 */
@supports(padding: max(0px)) {
  .header, .container {
    padding-left: max(15px, env(safe-area-inset-left));
    padding-right: max(15px, env(safe-area-inset-right));
  }

  .action-buttons {
    padding-bottom: max(20px, env(safe-area-inset-bottom));
  }
}
</style>